<template>
  <div class="discord-container pb-16 bg-gray-2600">
    <banner-top :aiNum="tool_count"
      :categoriesNum="category_count"></banner-top>
    <div class="index-content">
      <div class="max-w-11xl px-4 pt-5 pb-9 mx-auto">
        <index-menu-list></index-menu-list>
        <el-divider class="my-5"></el-divider>
        <index-categories-list :categories="category_group_list"></index-categories-list>

        <index-breadcrumbs label="discord_discordOfAI"></index-breadcrumbs>

        <div class="mt-5">
          <div class="flex items-center justify-between">
            <h2 class="text-34 text-gray-34 font-semibold">
              {{$t("discord_discordOfAI")}}
            </h2>
          </div>
          <div class="bg-white rounded-lg mt-5 p-4 sm:p-5">
            <div class="tTable"
              style="overflow-x: auto;"
              v-if="discordList && discordList.length>0"
              v-loading="sortLoading">
              <table style="width: 100%; min-width: 1160px;"
                class="fixTable">
                <thead>
                  <tr>
                    <th style="width: 5%">
                      <div class="cell text-md">
                        #
                      </div>
                    </th>
                    <th style="width: 18%">
                      <div class="cell text-md">
                        {{$t('discord_th_ais')}}
                      </div>
                    </th>
                    <th style="width: 18%">
                      <div class="cell text-md flex items-center gap-1.5">
                        <svg-icon iconName='discord'></svg-icon>
                        <span>{{$t('discord_th_discord')}}</span>
                      </div>
                    </th>
                    <th style="width: 8%">
                      <div class="cell sortBox">
                        <span class="text-sm">
                          {{$t('discord_th_members')}}
                        </span>
                        <div class="sort">
                          <div class="asc"
                            :class="{'actived':direction==='asc' && order_by==='user_num'}"
                            @click="sortChange(direction==='asc' && order_by==='user_num'?null:{order:'asc',prop:'user_num'})">
                            <svg-icon iconName='caret_up_default'></svg-icon>
                          </div>
                          <div class="desc"
                            :class="{'actived':direction==='desc' && order_by==='user_num'}"
                            @click="sortChange(direction==='desc' && order_by==='user_num'?null:{order:'desc',prop:'user_num'})">
                            <svg-icon iconName='caret_down_default'></svg-icon>
                          </div>
                        </div>
                      </div>
                    </th>
                    <th style="width: 17%">
                      <div class="cell sortBox">
                        <span class="text-sm">
                          {{$t('discord_th_7DayAvgOnlineUsers')}}
                        </span>
                        <div class="sort">
                          <div class="asc"
                            :class="{'actived':direction==='asc' && order_by==='online_num_7'}"
                            @click="sortChange(direction==='asc' && order_by==='online_num_7'?null:{order:'asc',prop:'online_num_7'})">
                            <svg-icon iconName='caret_up_default'></svg-icon>
                          </div>
                          <div class="desc"
                            :class="{'actived':direction==='desc' && order_by==='online_num_7'}"
                            @click="sortChange(direction==='desc' && order_by==='online_num_7'?null:{order:'desc',prop:'online_num_7'})">
                            <svg-icon iconName='caret_down_default'></svg-icon>
                          </div>
                        </div>
                      </div>
                    </th>
                    <th style="width: 34%">
                      <div class="cell text-md">
                        {{$t('discord_th_description')}}
                      </div>
                    </th>
                  </tr>
                </thead>
              </table>
              <table style="width: 100%; min-width: 1160px;"
                class="commonTable">
                <thead>
                  <tr>
                    <th style="width: 5%">
                      <div class="cell text-md">
                        #
                      </div>
                    </th>
                    <th style="width: 18%">
                      <div class="cell text-md">
                        {{$t('discord_th_ais')}}
                      </div>
                    </th>
                    <th style="width: 18%">
                      <div class="cell text-md flex items-center gap-1.5">
                        <svg-icon iconName='discord'></svg-icon>
                        <span>{{$t('discord_th_discord')}}</span>
                      </div>
                    </th>
                    <th style="width: 8%">
                      <div class="cell sortBox">
                        <span class="text-sm">
                          {{$t('discord_th_members')}}
                        </span>
                        <div class="sort">
                          <div class="asc"
                            :class="{'actived':direction==='asc' && order_by==='user_num'}"
                            @click="sortChange(direction==='asc' && order_by==='user_num'?null:{order:'asc',prop:'user_num'})">
                            <svg-icon iconName='caret_up_default'></svg-icon>
                          </div>
                          <div class="desc"
                            :class="{'actived':direction==='desc' && order_by==='user_num'}"
                            @click="sortChange(direction==='desc' && order_by==='user_num'?null:{order:'desc',prop:'user_num'})">
                            <svg-icon iconName='caret_down_default'></svg-icon>
                          </div>
                        </div>
                      </div>
                    </th>
                    <th style="width: 17%">
                      <div class="cell sortBox">
                        <span class="text-sm">
                          {{$t('discord_th_7DayAvgOnlineUsers')}}
                        </span>
                        <div class="sort">
                          <div class="asc"
                            :class="{'actived':direction==='asc' && order_by==='online_num_7'}"
                            @click="sortChange(direction==='asc' && order_by==='online_num_7'?null:{order:'asc',prop:'online_num_7'})">
                            <svg-icon iconName='caret_up_default'></svg-icon>
                          </div>
                          <div class="desc"
                            :class="{'actived':direction==='desc' && order_by==='online_num_7'}"
                            @click="sortChange(direction==='desc' && order_by==='online_num_7'?null:{order:'desc',prop:'online_num_7'})">
                            <svg-icon iconName='caret_down_default'></svg-icon>
                          </div>
                        </div>
                      </div>
                    </th>
                    <th style="width: 34%">
                      <div class="cell text-md">
                        {{$t('discord_th_description')}}
                      </div>
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <tr class="el-table__row"
                    v-for="(row, key) in discordList"
                    :key="key">
                    <td rowspan="1"
                      colspan="1"
                      class="el-table_1_column_1   el-table__cell">
                      <div class="cell">
                        <div class="text-center">
                          {{ key+1 }}
                        </div>
                      </div>
                    </td>
                    <td>
                      <div class="cell">
                        <div class="flex items-center gap-3.5 go-discord">
                          <common-link path="/discord/:handle"
                            :params="{ handle:row.discord_handle }"
                            target="_blank"
                            class="flex-shrink-0 w-14 h-14 rounded-lg overflow-hidden">
                            <common-image class="w-full h-full"
                              :src="row.avatar"
                              :alt="row.name"></common-image>
                          </common-link>
                          <div class="flex-1 w-0 truncate">
                            <common-link path="/discord/:handle"
                              :params="{ handle:row.discord_handle }"
                              target="_blank"
                              class="max-w-full text-base text-gray-1000 font-semibold hover:text-purple-1300"
                              :title="row.name">
                              {{row.name}}
                            </common-link>
                          </div>
                        </div>
                      </div>
                    </td>
                    <td>
                      <div class="cell">
                        <a :href="row.discord"
                          rel="nofollow"
                          :title="row.name"
                          target="_blank"
                          class="inline-block text-md text-blue-1800 hover:text-blue-1400 max-w-full line-2">
                          {{row.discord}}
                        </a>
                      </div>
                    </td>
                    <td>
                      <div class="cell">
                        <p class="text-md text-black break-words leading-7">
                          {{$vReset(row.user_num)}}
                        </p>
                      </div>
                    </td>
                    <td>
                      <div class="cell">
                        <p class="text-md text-black break-words leading-7">
                          {{$vReset(row.online_num_7)}}
                        </p>
                      </div>
                    </td>
                    <td>
                      <div class="cell">
                        <p class="text-md text-black break-words leading-7 line-2">
                          {{row.description}}
                        </p>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div class="mx-auto mt-6 text-center"
              v-if="discordList && discordList.length>0">
              <div class="mb-12 px-4"
                v-if="last_page>1">
                <link-pagination :order_by="order_by"
                  :direction="direction"
                  :page="page"
                  :step="_isMinSize() ? 2 : 3"
                  :last_page="last_page"
                  link="/discord"
                  pageLink="/discord/page/:page"></link-pagination>
              </div>
            </div>
            <el-empty v-if="(!discordList || discordList.length===0) && !loading"
              :description="$t('discord_end')"></el-empty>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import LinkPagination from '../../components/LinkPagination.vue'
export default {
  components: { LinkPagination },
  watchQuery: ['sort', 'order'],
  name: 'Free',
  head() {
    return {
      htmlAttrs: {
        lang: this.locale,
      },
      title: this.title,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: this.description,
        },
        {
          hid: 'og:title',
          name: 'og:title',
          content: this.title,
        },
        {
          hid: 'og:description',
          name: 'og:description',
          content: this.description,
        },
        {
          hid: 'og:url',
          name: 'og:url',
          content: this.canonicalLink,
        },
        {
          hid: 'og:image:alt',
          name: 'og:image:alt',
          content: this.title,
        },
      ],
      link: [
        {
          rel: 'canonical',
          href: this.canonicalLink,
        },
      ],
    }
  },
  async asyncData({ app, route, params, query, $axiosApi, error, store }) {
    try {
      let order_by = query && query.sort ? query.sort : null
      let direction = query && query.order ? query.order : null
      let [result] = await Promise.all([
        $axiosApi.getDiscord({
          page: params && params.page ? params.page : 1,
          per_page: 200,
          order_by: order_by,
          direction: direction,
        }),
      ])

      let res = {}
      if (result.code === 200) {
        res.discordList = result.data.data
        res.category_group_list = result.data.category_group_list

        res.total = result.data.total
        res.page = result.data.current_page ? result.data.current_page : 1
        res.next_page_url = result.data.next_page_url
          ? result.data.next_page_url
          : null

        res.tool_count = result.data.tool_count
        res.category_count = result.data.category_count
        res.last_page = result.data.last_page ? result.data.last_page : null
      } else {
        if (result && result.code && result.code === 404) {
          error({ statusCode: 404 })
        } else if (!(result && result.code && result.code === 401)) {
          error({
            message:
              'There is a problem with the network. Please refresh and try again later',
            statusCode: result.code,
          })
        }
      }

      let title = app.i18n.t('discord_page_title')
      let description = app.i18n.t('discord_page_detail')

      return {
        ...res,
        title,
        description,
        order_by,
        direction,
      }
    } catch (err) {
      console.log(err)
    }
  },
  data() {
    return {
      canonicalLink: `https://www.toolify.ai${this.$route.fullPath}`,
      title: null,
      description: null,

      category_group_list: [],

      tool_count: 0,
      category_count: 0,

      loading: false,
      sortLoading: false,
      discordList: [],
      page: 1,
      per_page: 200,
      next_page_url: null,
      last_page: null,
      total: 0,
      order_by: null,
      direction: null,
    }
  },
  computed: {
    ...mapState({
      countries: (state) => state.countries,
      locale: (state) => state.locale,
    }),
  },
  mounted() {
    window.addEventListener('scroll', this.onSroll)
  },
  methods: {
    onSroll() {
      if (
        !document.querySelector('.commonTable') ||
        !document.querySelector('.fixTable')
      ) {
        return false
      }
      const commonTable = document.querySelector('.commonTable')
      const fixTable = document.querySelector('.fixTable')

      const tableWidth = commonTable.offsetWidth
      const tableHeight = commonTable.offsetHeight
      const fixTableHeight = fixTable.offsetHeight
      const tableTop = commonTable.getBoundingClientRect().top
      const tableOffsetTop = commonTable.offsetTop
      const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
      if (
        tableWidth > 1160 &&
        tableTop <= 72 &&
        scrollTop < tableOffsetTop + tableHeight - fixTableHeight - 72
      ) {
        const distanceToLeft = commonTable.getBoundingClientRect().left
        const distanceToRight =
          window.innerWidth - commonTable.getBoundingClientRect().right

        fixTable.style.width = `${tableWidth}px`
        fixTable.style.zIndex = 10
        fixTable.style.left = `${distanceToLeft}px`
        fixTable.style.right = `${distanceToRight}px`
        fixTable.style.opacity = 1
      } else {
        fixTable.style.zIndex = -999
        fixTable.style.opacity = 0
      }
    },
    async getList(page) {
      this.loading = true
      try {
        const res = await this.$axiosApi.getDiscord({
          page: page,
          per_page: 200,
          order_by: this.order_by,
          direction: this.direction,
        })

        this.loading = false
        this.sortLoading = false

        if (res.code === 200) {
          if (page === 1) {
            this.discordList = res.data.data
          } else {
            this.discordList = this.discordList.concat(res.data.data)
          }
          this.total = res.data.total ? res.data.total : 0
          this.page = res.data.current_page ? res.data.current_page : 1
          this.next_page_url = res.data.next_page_url
            ? res.data.next_page_url
            : null
        }
      } catch (error) {
        console.log('error')
        this.loading = false
        this.sortLoading = false
      }
    },
    sortChange(column) {
      let query = {}
      if (column && column.order) {
        this.direction = column.order
        this.order_by = column.prop

        query = {
          sort: this.order_by,
          order: this.direction,
        }
      } else {
        this.direction = null
        this.order_by = null
      }

      this.sortLoading = true
      /* this.getList(1) */

      this.$router.replace({
        name: this.locale === 'en' ? 'discord' : 'lang-discord',
        query: query,
      })
    },
    _isMinSize() {
      if (process.browser) {
        const screenWidth = window.innerWidth
        return screenWidth < 1024
      } else {
        return false
      }
    },
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.onSroll, false)
  },
}
</script>
<style lang='scss' scoped>
.discord-container {
  ::v-deep .el-loading-mask {
    svg {
      margin-left: auto;
      margin-right: auto;
    }
  }
  .tTable {
    background: #ffffff;
    border: 1px solid #e5e5e5;
    border-radius: 6px;

    ::v-deep .el-loading-spinner {
      top: 100px;
      margin-top: 0px;
    }
    table {
      table-layout: fixed;
      td,
      th {
        box-sizing: border-box;
        min-width: 0;
        padding: 12px 0;
        position: relative;
        text-align: left;
        text-overflow: ellipsis;
        vertical-align: middle;
        .cell {
          box-sizing: border-box;
          display: inline-block;
          padding-left: 10px;
          padding-right: 10px;
          position: relative;
          vertical-align: middle;
          width: 100%;
          text-overflow: ellipsis;
          line-height: 23px;
          overflow: hidden;
        }
        &:first-child {
          .cell {
            padding-left: 14px;
            text-align: center;
          }
        }
        &:last-child {
          .cell {
            padding-right: 14px;
          }
        }
      }
      &.fixTable {
        position: fixed;
        top: 72px;
        z-index: 10;
      }
      thead {
        tr {
          th {
            background: #f8f9fb;
            color: #666;
            font-weight: 400;
            border-bottom: 1px solid #e5e5e5;
            .sortBox {
              display: flex;
              align-items: center;
              .sort {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                margin-left: 4px;
                .asc,
                .desc {
                  width: 8px;
                  height: 8px;
                  cursor: pointer;
                  svg {
                    font-size: 8px;
                    fill: #999;
                  }
                  &.actived {
                    svg {
                      fill: #7150e6;
                    }
                  }
                }
                .desc {
                  margin-top: 1px;
                }
              }
            }
          }
        }
      }
      tbody {
        tr {
          td {
            border-bottom: 1px solid #e5e5e5;
            color: #191919;
            font-size: 16px;
            padding-bottom: 16px;
            padding-top: 16px;
            transition: background-color 0.25s ease;
            .no-color {
              color: rgba(0, 0, 0, 0);
            }
            .no-color {
              color: rgba(0, 0, 0, 0);
            }
          }
          &:hover {
            td {
              background-color: #f5f7fa;
            }
          }

          &:last-child {
            td {
              border-bottom: 0;
            }
          }
        }
      }
    }
  }
}
</style>
